<?php

declare(strict_types=1);

namespace App\Robot\Crontab;

use App\CustHub\Service\ChSmartPushSchemeTargetTaskService;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Support\optional;

class SmartPushTargetCrontab
{
    public function execute(): string
    {
        //使用锁避免任务多次执行
        $lockKey = "smart_push_target_lock_" . time();
        $lock = lock($lockKey, 10);
        try {
            $lock->block(5);
            container()->get(ChSmartPushSchemeTargetTaskService::class)->timedHandler();
            return '智能推送目标任务执行完毕';
        } catch (LockTimeoutException $e) {
            logger("智能推送目标任务执行完毕" . $e->getMessage());
            return '智能推送单次任务执行完毕';
        } catch (\Throwable $e) {
            logger("智能推送目标任务执行完毕" . $e->getMessage());
            optional($lock)->release();
            return '智能推送目标任务执行完毕';
        } finally {
            $lock->release();
        }
    }
}